package com.powernode.model;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

/**
 * 统一权限用户对象类
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class SecurityUser implements UserDetails {
    // 编号
    private Long userId;
    // 用户名
    private String username;
    // 密码
    private String password;
    // 登录类型
    private String loginType;
    // 状态码
    private Integer status;
    // 店铺标识
    private Long shopId;
    /**
     * 用户权限
     */
    private Set<String> perms = new HashSet<>();
    // TODO 用户购物车系统用户属性还未添加

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return null;
    }

    @Override
    public String getPassword() {
        return this.password;
    }

    /**
     * 在Spring Security框架中用户的username唯一身份，不能重复
     * @return
     */
    @Override
    public String getUsername() {
        return this.loginType + this.userId;
    }

    @Override
    public boolean isAccountNonExpired() {
        return this.status == 1;
    }

    @Override
    public boolean isAccountNonLocked() {
        return this.status == 1;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return this.status == 1;
    }

    @Override
    public boolean isEnabled() {
        return this.status == 1;
    }

    /**
     * 处理用户权限记录中包含多个权限格式化的情况
     * @param perms
     */
    public void setPerms(Set<String> perms) {
        HashSet<String> finalPermsSet = new HashSet<>();
        perms.forEach(perm -> {
            // 判断是否包含分隔,
            if (perm.contains(",")) {
                // 需要进行拆分
                String[] realPerams = perm.split(",");
                // 将数据插入最终权限集合中
                finalPermsSet.addAll(Arrays.asList(realPerams));
            } else {
                finalPermsSet.add(perm);
            }
        });
        this.perms = finalPermsSet;
    }
}
